package inutan.match;

import org.ricks.common.lang.Logger;
import org.ricks.common.lang.Sequence;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class GroupRoom {

    /**
     *  房间号分配器
     */
    private static final Sequence sequence = new Sequence();
    private final int roomEnum;

    /**
     * 房间允许进入最大人数，从策划表读取
     */
    private int roomMaxCount = 16;

    /**
     * 房间ID ，房间内角色信息
     */

    private Map<Long,GroupUnit> roomGroupMap = new ConcurrentHashMap<>();

    public GroupRoom(int roomEnum) {
        this.roomEnum = roomEnum;
    }


    /**
     * 玩家加入房间
     * @param roomId
     * @param userBaseInfo
     */
    public void join(long roomId, UserBaseInfo userBaseInfo) {
        GroupUnit groupUnit = this.roomGroupMap.get(roomId);
        if (groupUnit == null) {
            groupUnit = new GroupUnit();
            this.roomGroupMap.put(roomId, groupUnit);
        }
        groupUnit.groupMap.put(userBaseInfo.getUserId() ,userBaseInfo);
    }

    public void remove(long roomId, long userId) {
        GroupUnit groupUnit = this.roomGroupMap.get(roomId);
        groupUnit.groupMap.remove(userId);
    }

    public void remove(long userId) {
        for (long roomId : roomGroupMap.keySet()) {
            remove(roomId, userId);
            Logger.info(userId + ": 正在从房间管理移除, roomType:"+roomEnum+" --  roomId:" + roomId);
        }
    }

    public Map<Long, UserBaseInfo> get(long roomId) {
        return roomGroupMap.get(roomId).groupMap;
    }

    /**
     * 创建房间唯一编号
     * @return
     */
    public long createRoomId() {
        return sequence.nextId();
    }

    private class GroupUnit {
        Map<Long, UserBaseInfo> groupMap = new HashMap<>(roomMaxCount);
    }
}
